﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using ComicIsland.Common.StorageHelper;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.CacheDownload
{
    public partial class ComicCacheManagePage : PhoneApplicationPage
    {
        private bool IsReloadData = false;
        private DownloadComic downloadComic = null;

        public ComicCacheManagePage()
        {
            InitializeComponent();
            IsReloadData = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            IsReloadData = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            InitialTransferStatusCheck();
            //
            if (base.NavigationContext.QueryString.ContainsKey("DownloadComic"))
            {
                string paramDownloadComic = string.Empty;
                base.NavigationContext.QueryString.TryGetValue("DownloadComic", out paramDownloadComic);
                if (string.IsNullOrWhiteSpace(paramDownloadComic))
                {
                    base.NavigationService.GoBack();
                    return;
                }
                downloadComic = JSONHelper.Deserialize<DownloadComic>(paramDownloadComic);
                if (downloadComic == null)
                {
                    base.NavigationService.GoBack();
                    return;
                }
                if (IsReloadData)
                {
                    //新增或更新本地缓存（要下载漫画的缓存列中）
                    this.InsertOrUpdateLocalCache();
                    //TODO 添加至下载队列中去                    
                }
            }

            //加载下载过的漫画列表
            if (IsReloadData)
            {
                LoadDownloadQueueComics();
            }
        }


        /// <summary>
        /// 新增或更新本地缓存
        /// </summary>
        void InsertOrUpdateLocalCache()
        {
            if (!IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
                return;

            string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
            if (string.IsNullOrWhiteSpace(localCacheData))
                return;
            var localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
            bool isUpdate = false;
            if (localCacheItems != null && localCacheItems.Count > 0)
            {
                foreach (DownloadComic item in localCacheItems)
                {
                    if (item.ComicId == downloadComic.ComicId)
                    {
                        //已经存在则需要一一比对
                        isUpdate = true;
                        if (!(downloadComic != null && downloadComic.Chapters != null && downloadComic.Chapters.Count > 0))
                            return;
                        foreach (var currentItem in downloadComic.Chapters)
                        {
                            var isExist = (from p in item.Chapters where p.PartId == currentItem.PartId select p).FirstOrDefault<DownloadComicChapter>();
                            if (isExist == null)
                            {
                                if (!(item.Chapters != null && item.Chapters.Count > 0))
                                    item.Chapters = new ObservableCollection<DownloadComicChapter>();
                                item.Chapters.Add(currentItem);
                            }
                        }
                        break;
                    }
                }
                //如果是更新则需要一一比对来进行数据更新，如果是false则直接加入列表
                if (!isUpdate)
                {
                    localCacheItems.Add(downloadComic);
                }
                string jsonSerialize = JSONHelper.Serialize<ObservableCollection<DownloadComic>>(localCacheItems);
                IsolatedStorageHelper.Instance.WriteText(jsonSerialize, KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
            }
            else
            {
                string jsonSerialize = JSONHelper.Serialize<ObservableCollection<DownloadComic>>(new ObservableCollection<DownloadComic>() { downloadComic });
                IsolatedStorageHelper.Instance.WriteText(jsonSerialize, KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
            }
        }


        #region ******************************加载缓存的漫画列表及其多选删除操作等******************************
        /// <summary>
        /// 加载缓存的漫画列表
        /// </summary>
        void LoadDownloadQueueComics()
        {
            if (!IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
                return;

            string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
            if (string.IsNullOrWhiteSpace(localCacheData))
                return;
            var localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
            if (!(localCacheItems != null && localCacheItems.Count > 0))
            {
                //为空，则不处理
                return;
            }
            foreach (DownloadComic item in localCacheItems)
            {
                if (item == null)
                    continue;
                if (!(item.Chapters != null && item.Chapters.Count > 0))
                    continue;
                item.Total = item.Chapters.Count;
                item.TotalCompleted = item.Chapters.Where(p => p.DownloadStatus == (int)DownloadComicChapterStatus.Completed).Count();
            }
            this.Dispatcher.BeginInvoke(() =>
            {
                this.llms.ItemsSource = localCacheItems;
            });
        }

        private void appBarDelete_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if ("选择".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "删除";
                    appBarIcon.IconUri = new Uri("/Images/Icons/delete.png", UriKind.Relative);
                    appBarIcon.IsEnabled = false;
                    this.llms.IsSelectionEnabled = true;
                }
                else
                {
                    if (MessageBoxResult.OK == MessageBox.Show(string.Format("确认删除选中的 {0} 个缓存漫画？", this.llms.SelectedItems.Count), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
                    {
                        if (!IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
                            return;

                        string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
                        if (string.IsNullOrWhiteSpace(localCacheData))
                            return;
                        var localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
                        //
                        var source = this.llms.ItemsSource as ObservableCollection<DownloadComic>;
                        while (this.llms.SelectedItems.Count > 0)
                        {
                            var item = this.llms.SelectedItems[0] as DownloadComic;
                            if (item != null)
                            {
                                if (localCacheItems != null && localCacheItems.Count > 0)
                                {
                                    for (int i = 0; i < localCacheItems.Count; i++)
                                    {
                                        DownloadComic dc = localCacheItems[i];
                                        if (dc == null)
                                            continue;
                                        if (item.ComicId == dc.ComicId && item.ComicTitle.Equals(dc.ComicTitle))
                                        {
                                            localCacheItems.Remove(dc);
                                            break;
                                        }
                                    }
                                }
                                source.Remove(item);
                            }
                        }
                        //更新本地缓存
                        string text = JSONHelper.Serialize<ObservableCollection<DownloadComic>>(localCacheItems);
                        IsolatedStorageHelper.Instance.WriteText(text, KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
                    }
                    //
                    appBarIcon.Text = "选择";
                    appBarIcon.IconUri = new Uri("/Images/Icons/select.png", UriKind.Relative);
                    appBarIcon.IsEnabled = true;
                    this.llms.IsSelectionEnabled = false;
                }
            });
        }

        private void llms_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.llms.IsSelectionEnabled)
            {
                bool hasSelection = ((this.llms.SelectedItems != null) && (this.llms.SelectedItems.Count > 0));
                var appBarIcon = ApplicationBar.Buttons[0] as ApplicationBarIconButton;
                if (appBarIcon == null)
                    return;
                appBarIcon.IsEnabled = hasSelection;
            }
            else
            {
                bool hasSelection = ((this.llms.SelectedItems != null) && (this.llms.SelectedItems.Count > 0));
                var appBarIcon = ApplicationBar.Buttons[0] as ApplicationBarIconButton;
                if (appBarIcon == null)
                    return;

                if ("删除".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "选择";
                    appBarIcon.IconUri = new Uri("/Images/Icons/select.png", UriKind.Relative);
                    appBarIcon.IsEnabled = true;
                    this.llms.IsSelectionEnabled = false;
                }
            }
        }
        #endregion  ******************************加载缓存的漫画列表及其多选操作等******************************

        private void gridComic_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            DownloadComic item = (sender as Grid).DataContext as DownloadComic;
            if (item == null)
                return;
            string param = string.Concat("?DownloadComic=", Uri.EscapeDataString(JSONHelper.Serialize<DownloadComic>(item)));
            NaviService.Navigate(ComicIslandPage.CDComicChapterCacheQueuePage, param);

        }


        #region ******************************下载队列数据更新******************************
        private IEnumerable<BackgroundTransferRequest> transferRequests;
        private void InitialTransferStatusCheck()
        {
            UpdateRequestsList();

            foreach (var transfer in transferRequests)
            {
                transfer.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
                transfer.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
                ProcessTransfer(transfer);
            }
        }

        /// <summary>
        /// 该方法使用 BackgroundTransferService 类的 Requests 属性检索当前已为该应用注册的传输请求列表。
        /// <para>该属性返回新 BackgroundTransferRequest 对象的列表。</para>
        /// <para>由于对象是新的，因此请确保针对任何现有对象引用调用 Dispose 以避免内存泄露。</para>
        /// </summary>
        private void UpdateRequestsList()
        {
            // The Requests property returns new references, so make sure that
            // you dispose of the old references to avoid memory leaks.
            if (transferRequests != null)
            {
                foreach (var request in transferRequests)
                {
                    request.Dispose();
                }
            }
            if (BackgroundTransferService.Requests.Count() <= 0)
            {
                //TODO 添加下载队列
            }
            transferRequests = BackgroundTransferService.Requests;
        }

        void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            ProcessTransfer(e.Request);
            UpdateUI();
        }

        void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            UpdateUI();
        }

        private void ProcessTransfer(BackgroundTransferRequest transfer)
        {
            switch (transfer.TransferStatus)
            {
                case TransferStatus.Completed:

                    // If the status code of a completed transfer is 200 or 206, the
                    // transfer was successful
                    if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
                    {
                        //从队列移除
                        RemoveTransferRequest(transfer.RequestId);
                        //
                        DownloadComicChapterImage dcci = JSONHelper.Deserialize<DownloadComicChapterImage>(transfer.Tag);
                        string filefullpath = string.Empty;
                        if (dcci == null)
                        {
                            return;
                        }
                        string filename = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, dcci.ComicId, "_", dcci.PartId, "_", MD5.GetMd5String(dcci.ImageUrl));
                        LogHelper.LogInfo(filename, this.GetType(), MethodBase.GetCurrentMethod());

                        //将下载的文件移到指定目录下
                        using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            try
                            {
                                if (!isoStore.FileExists(filename))
                                {
                                    //isoStore.DeleteFile(filename);
                                    isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename);
                                }
                            }
                            catch (Exception err)
                            {
                                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                            }
                        }
                        //更新缓存状态
                        string key = string.Format(KEYS.CACHEDOWNLOAD_CHAPTER_IMAGE_QUEUE, dcci.ComicId, dcci.PartId);
                        if (!IsolatedStorageHelper.Instance.FileExists(key))
                        {
                            return;
                        }
                        string text = IsolatedStorageHelper.Instance.ReadText(key);
                        var items = JSONHelper.Deserialize<ObservableCollection<DownloadComicChapterImage>>(text);

                        if (items != null && items.Count > 0)
                        {
                            foreach (DownloadComicChapterImage itemDcci in items)
                            {
                                if (itemDcci.ComicId == dcci.ComicId && itemDcci.PartId == dcci.PartId && itemDcci.ImageUrl.Equals(dcci.ImageUrl))
                                {
                                    itemDcci.DownloadStatus = (int)DownloadComicChapterStatus.Completed;
                                    break;
                                }
                            }
                            var newText = JSONHelper.Serialize<ObservableCollection<DownloadComicChapterImage>>(items);
                            IsolatedStorageHelper.Instance.WriteText(newText, key, true);
                        }
                        //是否下载完成
                        if (items != null && items.Count > 0)
                        {
                            bool isDownloadAll = true;
                            foreach (DownloadComicChapterImage itemDcci in items)
                            {
                                if (itemDcci == null)
                                    continue;
                                if (itemDcci.DownloadStatus == (int)DownloadComicChapterStatus.Downloading || itemDcci.DownloadStatus == (int)DownloadComicChapterStatus.Pending)
                                {
                                    isDownloadAll = false;
                                    break;
                                }
                            }
                            if (isDownloadAll)//TODO 全部下载完成，标识章节为下载完成
                            {
                                UpdateLocalCacheFromDownloadComicChapter(dcci.ComicId, dcci.PartId, DownloadComicChapterStatus.Completed);
                            }
                        }
                    }
                    else
                    {
                        //下载不正确时，从队列移除或做其它处理
                        RemoveTransferRequest(transfer.RequestId);

                        if (transfer.TransferError != null)
                        {
                            //还有队列则继续处理
                        }
                    }
                    break;
            }
        }

        private void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);
            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        private void UpdateUI()
        {
            UpdateRequestsList();
        }
        #endregion ******************************下载队列数据更新******************************


        /// <summary>
        /// 更新漫画中章节下载状态的缓存数据
        /// </summary>
        /// <param name="comicId"></param>
        /// <param name="partId"></param>
        /// <param name="status"></param>
        void UpdateLocalCacheFromDownloadComicChapter(int comicId, int partId, DownloadComicChapterStatus status)
        {
            ObservableCollection<DownloadComic> localCacheItems = null;
            if (IsolatedStorageHelper.Instance.FileExists(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE))
            {
                string localCacheData = IsolatedStorageHelper.Instance.ReadText(KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE);
                if (!string.IsNullOrWhiteSpace(localCacheData))
                {
                    localCacheItems = JSONHelper.Deserialize<ObservableCollection<DownloadComic>>(localCacheData);
                }
            }
            if (localCacheItems != null && localCacheItems.Count > 0)
            {
                foreach (DownloadComic dc in localCacheItems)
                {
                    if (dc == null)
                        continue;
                    if (dc.ComicId != comicId)
                        continue;
                    foreach (DownloadComicChapter dcDcc in dc.Chapters)
                    {
                        if (dcDcc == null)
                            continue;
                        if (dcDcc.PartId == partId)
                        {
                            dcDcc.DownloadStatus = (int)DownloadComicChapterStatus.Completed;
                            break;
                        }
                    }
                }
            }
            IsolatedStorageHelper.Instance.WriteText(JSONHelper.Serialize<ObservableCollection<DownloadComic>>(localCacheItems), KEYS.CACHEDOWNLOAD_CHAPTER_QUEUE, true);
        }
    }
}